﻿using System.Collections.Generic;
using System.Linq;
using TelerikMvcGridCustomBindingHelper.Mapper;

namespace TelerikMvcGridCustomBindingHelper.Projections
{
    public class ProjectionExpression<TSource> : IProjectionExpression<TSource>
    {
        private readonly IQueryable<TSource> _source;
        private readonly ProjectionsEngine _projectionsEngine = new ProjectionsEngine();

        public ProjectionExpression(IQueryable<TSource> source)
        {
            _source = source;
        }

        public IEnumerable<TResult> To<TResult>() where TResult : class
        {
            GridModelMapper.AssertMappings<TSource, TResult>();

            var expr = _projectionsEngine.CreateMapExpressionTo<TSource, TResult>();

            return _source.Select(expr);
        }

        public IEnumerable<TSource> From<TResult>() where TResult : class
        {
            GridModelMapper.AssertMappings<TSource, TResult>();

            var expr = _projectionsEngine.CreateMapExpressionFrom<TSource, TResult>();

            return _source.Select(expr);
        }
    }
}
